/* eslint no-constant-condition: ["error", { "checkLoops": false }] */
/**
 *
 * Copyright 2016-present teaming
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
import { put, take, call, fork } from 'redux-saga/effects';

import * as types from '../constants/ActionTypes';
import ToastUtil from '../utils/ToastUtil';
import RequestXhrUtil from '../utils/RequestXhrUtil';
import { WEXIN_TEAM_LIST, SCRM_API } from '../constants/Urls';
import { fetchAllMemberList, receiveAllMemberList } from '../actions/member';

export function* requestAllMemberList(
  token,
  site_id,
  format,
  loading
) {
  try {
    yield put(fetchAllMemberList(loading));

    let queryString = '';
    let qsArr = [];
    if (format) qsArr.push(`format=${format}`)
    if (site_id) qsArr.push(`site_id=${site_id}`)
    if (qsArr.length) queryString = '?' + qsArr.join('&')
    
    const response = yield call(
      RequestXhrUtil.request,
      `${SCRM_API}/users/${token}/site_users${queryString}`,
      'get'
    );
    yield put(receiveAllMemberList(
      response.results,
      false
    ));
    const errorMessage = response.errmsg;
    if (response.errcode && errorMessage !== '') {
      yield ToastUtil.showShort(errorMessage);
    }
  } catch (error) {
    yield put(receiveAllMemberList([], false));
    ToastUtil.showShort('网络发生错误，请重试');
  }
}

export function* watchRequestAllMemberList() {
  while (true) {
    const {
      token,
      site_id,
      format,
      loading
    } = yield take(types.REQUEST_ALL_MEMBER_LIST);
    yield fork(
      requestAllMemberList,
      token,
      site_id,
      format,
      loading
    );
  }
}
